package cn.tedu._03vehicle.base.interceptors;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import java.time.LocalDateTime;
import java.util.concurrent.ConcurrentHashMap;

//网站限流拦截器 单个ip限制每分钟访问网站不超过3次 超过三次认为该客户有攻击风险
@Slf4j
public class RateLimitInterceptor implements HandlerInterceptor {
    public static final int MAX_COUNT = 3;
    public static final int MAX_WINDOW_SIZE = 60;

    private final ConcurrentHashMap<String, Integer> clientCounts
            = new ConcurrentHashMap<>();
    private final ConcurrentHashMap<String, LocalDateTime> lastResetTimes
            = new ConcurrentHashMap<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.debug("进入网站限流的拦截器");
        String clientIp = request.getRemoteAddr();
        LocalDateTime lastResetTime = lastResetTimes.get(clientIp);
        /**
         * 关于lastResetTime 判断
         *1 null
         * 2 是否在60秒内 以外 非空
         * 3            以外 非空
         */
        if (lastResetTime == null || LocalDateTime.now().isAfter(lastResetTime.plusSeconds
                (MAX_WINDOW_SIZE))){
            clientCounts.put(clientIp, 0);//计数器清零；
            lastResetTimes.put(clientIp, LocalDateTime.now());//更新时间
        }
        //计数器加1
        Integer count = clientCounts.get(clientIp);
        count=count+1;
        clientCounts.put(clientIp, count);
        //和3比较
        if (count > MAX_COUNT){
            throw new RuntimeException("非常抱歉，您访问的太频繁了");
        }
        return true;//放行
    }
}

